package dao;

import baperjakat.Koneksi;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import model.Jabatan;

/**
 *
 * @author Marlon
 */
public class JabatanDao {
    private Connection c;
    private PreparedStatement p;
    private Statement s;
    
    public JabatanDao(){
        c = Koneksi.getKoneksi();
    }
    
    public void insert(Jabatan j) throws SQLException {
        p = c.prepareStatement("INSERT INTO jabatan (eselon, namajabatan) VALUES ( ?, ?)");
        simpan(j, p);
    }

    public void update(Jabatan j) throws SQLException {
        p = c.prepareStatement("UPDATE jabatan SET eselon = ? where namajabatan = ?");
        simpan(j, p);
    }
    
    public void delete(Jabatan j) throws SQLException {
        p = c.prepareStatement("DELETE FROM jabatan WHERE namajabatan = ?");
            
        p.setString(1, j.getJabatan());
        p.executeUpdate();
        p.close();
    }

    public void simpan(Jabatan j, PreparedStatement p) throws SQLException{
        
        p.setString(2,j.getJabatan());
        p.setString(1,j.getEselon());
        
        p.executeUpdate();
        p.close();
    }

    public Jabatan getByNama(String jabatan) throws SQLException {
        p = c.prepareStatement("SELECT * FROM jabatan WHERE namajabatan = ?");
        p.setString(1, jabatan);
        ResultSet r = p.executeQuery();
        
        if(!r.next())
            return null;

        Jabatan j = new Jabatan();
        j.setId(r.getString("idjabatan"));
        j.setJabatan(r.getString("namajabatan"));
        j.setEselon(r.getString("eselon"));
        
        r.close();
        p.close();

        return j;
    }
    
     public List<Jabatan> getAll() throws SQLException {
        List<Jabatan> listJabatan = new ArrayList<>();
        
        s = c.createStatement();
        String sql = "SELECT * FROM jabatan";
        ResultSet r = s.executeQuery(sql);
        
        Jabatan j = null;
        while(r.next()){
            j = new Jabatan();
            j.setId(r.getString("idjabatan"));
            j.setJabatan(r.getString("namajabatan"));
            j.setEselon(r.getString("eselon"));
            
            listJabatan.add(j);
        }
        
        r.close();
        s.close();

        return listJabatan;
    }
}

